using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MVCWeb.Helpers;
using MVCWeb.Models.ViewData;
using MVCWeb.Models;

namespace MVCWeb.Controllers
{
    public class CompanyController : BaseController
    {
        private const int defaultPageSize = 10;
        //
        // GET: /Company/


        public ActionResult Index(int? page)
        {
            int currentPage = page.HasValue ? page.Value - 1 : 0;
            return View(dc.Companies.ToPagedList(currentPage, defaultPageSize));
        }

        //
        // GET: /Company/Details/5

        public ActionResult Details(int id)
        {
            Company company = dc.Companies.First<Company>(c => c.CompanyId == id);
            return View(company);
        }

        //
        // GET: /Company/Create

        public ActionResult Create()
        {
            CompanyNewViewData data = new CompanyNewViewData();
            data.Users = dc.Users.ToList<User>();
            return View(data);
        }


        public ActionResult CreateUser()
        {
            return View();
        }

        //
        // POST: /Company/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Company companyToCreate)
        {
            try
            {
                if (string.IsNullOrEmpty(companyToCreate.Name))
                {
                    ModelState.AddModelError("Name", "Company name must be entered");
                }
                if (ModelState.IsValid)
                {
                    // TODO: Add insert logic here
                    UpdateModel<Company>(companyToCreate);
                    dc.SubmitChanges();
                    return RedirectToAction("Index");
                }

                CompanyNewViewData data = new CompanyNewViewData();
                data.Users = dc.Users.ToList<User>();
                return View(data);
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Company/Edit/5
 
        public ActionResult Edit(int id)
        {
            Company company = dc.Companies.First<Company>(c => c.CompanyId == id);
            return View(company);
        }

        //
        // POST: /Company/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                Company company = dc.Companies.First<Company>(c => c.CompanyId == id);
                UpdateModel<Company>(company);
                dc.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
